from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext, loader, Context
from django.http import HttpResponseRedirect
from math import ceil
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from models import SearchEngine, RSS, Favorites
from django.core.urlresolvers import reverse

def index(request):
  # Render view, we can pass data to it.
  return newsByCategory(request, "");

def appendResults(currentResults, indexOfResults, method):
  for result in currentResults:
    result[indexOfResults] = method(result['title'])

  return currentResults


def chunks(full_list, size):
    if len(full_list) > 0:
      return [full_list[i:i+size] for i in range(0, len(full_list), size)]
    else:
      return []
  
# Manage a single RSS, delete/show/edit
def rssManage(request, rssId):
  # If GET, remove RSS from user
  if request.method == 'GET':
    user = User.objects.get(id=request.user.id)
    rss = user.rss_set.get(id=rssId)
    user.rss_set.remove(rss)

  # Redirect to home
  return HttpResponseRedirect(reverse('home'))

# Manage RSS in general, eg. create
def rssManager(request):
  # If POST
  if request.method == 'POST':
    rss_id = request.POST.get('rss_id', '')

    # If the RSS was valid, associate user and rss
    if rss_id.isdigit() and RSS.objects.filter(id=rss_id):
      rss = RSS.objects.get(id=rss_id)
      User.objects.get(id=request.user.id).rss_set.add(rss)

  # Redirect to home
  return HttpResponseRedirect(reverse('home'))

# Manage RSS in general, eg. create
def favoriteEdit(request):
  # If POST
  if request.method == 'POST':
    favorites = []
    favorites.append(request.POST.get('favorite1', ''))
    favorites.append(request.POST.get('favorite2', ''))
    favorites.append(request.POST.get('favorite3', ''))
    favorites.append(request.POST.get('favorite4', ''))
    favorites.append(request.POST.get('favorite5', ''))
    favorites.append(request.POST.get('favorite6', ''))
    favorites.append(request.POST.get('favorite7', ''))

    # Set missing to default
    if (favorites[0] == ""):
      favorites[0] = 'Business'
    if (favorites[1] == ""):
      favorites[1] = 'Sport'
    if (favorites[2] == ""):
      favorites[2] = 'Art'
    if (favorites[3] == ""):
      favorites[3] = 'Entertainment'
    if (favorites[4] == ""):
      favorites[4] = 'Technology'
    if (favorites[5] == ""):
      favorites[5] = 'Fashion'
    if (favorites[6] == ""):
      favorites[6] = 'Finance'

    user = User.objects.get(id=request.user.id)
    favoritesDb = Favorites.objects.filter(user_id=request.user.id)
    for f in favoritesDb:
      f.delete()

    for i in range(0,7):
      Favorites(search=favorites[i], user_id=request.user.id).save()

    return HttpResponseRedirect(reverse('home'))

  # IF GET
  else:
      # Load categories and render template
      templateData = {}
      templateData['favorites'] = []
      query = Favorites.objects.filter(user_id=request.user.id)
      for elem in query:
        templateData['favorites'].append(elem)

      while len(templateData['favorites']) < 7:
        templateData['favorites'].append("")

      return render_to_response('main/edit_favorites.html', templateData, context_instance = RequestContext(request))

  # Redirect to home
  return HttpResponseRedirect(reverse('home'))

def newsByCategory(request, category):
  searchEngine = SearchEngine()

  query_string = request.GET.get('keyword', '')

  # Get data
  result_dict = {}
  web_results = searchEngine.queryForNews(query_string, category);

  # split webresults into 3 cols
  nrElem = len(web_results)
  foo = nrElem / 3.0
  perColumn = int(ceil(foo))
  web_results = chunks(web_results, perColumn)

  if request.user.is_authenticated():
    web_results = addRSSToWebResults(web_results, request)
    result_dict['unrelatedRSS'] = getUnrelatedRSS(request)

  result_dict['web_results'] = web_results
  result_dict['query_string'] = query_string;

  # Render view, we can pass data to it.
  return render_to_response('main/news.html', result_dict, context_instance = RequestContext(request))

def addRSSToWebResults(web_results, request):
  rss_feeds = {}
  rss_feeds['rss'] = True

  user = User.objects.get(id=request.user.id)
  rss = user.rss_set.all()

  result = []
  for elem in rss:
    # Fetch
    entries = []
    entries = elem.fetchRSS()['entries'][0:4]
    elemContainer = []
    elemContainer.append(elem.name)
    elemContainer.append(elem.id)
    entries.insert(0, elemContainer)
    result.append(entries)

  # Fetch RSS
  rss_feeds['feeds'] = result
#  print rss_feeds['feeds']['BBC world'][0]['summary']

  # Add to top of third column
  while (len(web_results) < 3):
    web_results.append([])

  web_results[2].insert(0,rss_feeds)

  return web_results

def getUnrelatedRSS(request):
  user = User.objects.get(id=request.user.id)
  rss = user.rss_set.all()
  return RSS.objects.exclude(id__in = rss)

def contact(request):
  return render_to_response('main/contact.html', context_instance = RequestContext(request))

def login(request):
  return render_to_response('registration/login.html', context_instance = RequestContext(request))
  
def logout(request):
  return render_to_response('registration/logout.html', context_instance = RequestContext(request))
  
def change_password(request):
  return render_to_response('registration/password_change_form.html', context_instance = RequestContext(request))
 
def forgotten(request):
  return render_to_response('registration/password_reset_form.html', context_instance = RequestContext(request))
  
def register(request):
#  # Get data from POST
  username = request.POST.get('username', '')
  password1 = request.POST.get('password1', '')
  password2 = request.POST.get('password2', '')
  email = request.POST.get('email', '');
  # Create user if data ok
  # @todo Validation.
  if (username != '' and password1 != '' and password1 == password2 and email != ''):
    return HttpResponse("lol");

  # If get-request, simply:
  return render_to_response('main/register.html', context_instance = RequestContext(request))

def userpage(request):
  profile = UserProfile()
  link=profile.test();
  
  return render_to_response('main/user_settings.html', context_instance = RequestContext(request))
  
# eg. http://localhost:8000/ajax/additionaldata/?keyword=gothenburg&type=video
def ajax_getAdditionalData(request):
  searchEngine = SearchEngine()
  keyword = request.GET.get('keyword', '')

  pictures = {}
  videos = {}

  if keyword != '':
    videos['data'] = searchEngine.queryForVideos(keyword)
    pictures['data'] = searchEngine.queryForPictures(keyword)
  else:
    return HttpResponse('')

  if (len(videos['data']) + len(pictures['data'])) == 0:
    return HttpResponse('')

  picture_template = loader.get_template('ajax/search_picture.html')
  video_template = loader.get_template('ajax/search_video.html')

  response = video_template.render(Context(videos));
  response = response + picture_template.render(Context(pictures));

  return HttpResponse(response);
  
def ajaxtest(request):
  return HttpResponse("Do you mean: \"Newstopia\"? ");  

def users(request):
  return render_to_response('main/userhome.html', context_instance = RequestContext(request))
